package com.gjy.rabbitmq.resolve;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

/**
 * 演示如何使用可靠消息生产和消费
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-13 14:48:37
 */
public class ReliableMessagingExample {
    private static final Logger logger = LoggerFactory.getLogger(ReliableMessagingExample.class);

    public static void main(String[] args) {
        logger.info("启动可靠消息传递示例");

        try {
            // 初始化可靠配置
            ReliableRabbitMQConfig config = new ReliableRabbitMQConfig();
            config.initialize();
            Channel channel = config.getChannel();

            // 创建可靠生产者
            ReliableMessageProducer producer = new ReliableMessageProducer(channel);
            logger.info("创建可靠消息生产者");

            // 发送可靠消息
            for (int i = 0; i < 10; i++) {
                String message = "可靠消息 " + i;
                producer.sendReliableMessage("reliable.exchange", "reliable.routing.key", message);
                logger.info("发送消息: {}", message);
            }

            // 创建可靠消费者
            IdempotentMessageProcessor processor = new IdempotentMessageProcessor(
                    new RedisUtil(new JedisPool("localhost", 6379)),
                    new BusinessService()
            );

            ReliableMessageConsumer consumer = new ReliableMessageConsumer(channel, processor);
            String consumerTag = consumer.consumeMessages("reliable.queue");
            logger.info("创建可靠消息消费者: consumerTag={}", consumerTag);

            logger.info("示例启动完成，等待消息处理...");

            // 保持程序运行60秒
            Thread.sleep(60000);

            // 清理资源
            config.close();
            logger.info("示例运行结束");

        } catch (Exception e) {
            logger.error("可靠消息传递示例运行失败", e);
        }
    }

}
